import {toString} from "./string"
import {isSafeInteger, isNaN} from "../origin/number";

/**
 * 阿拉伯整数数字转汉字
 *
 * @category Number
 * @param { string | number} num
 * @returns {string}
 * @example
 *
 * num2Chinese(1.1)
 * // => 一
 */
const num2Chinese = (num: string | number | any) => {
    const numMap = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const scale1 = ['', '十', '百', '千'];
    const scale2 = ['', '万', '亿', '兆'];

    if (isNaN(num) && !isSafeInteger(num)) {
        return num;
    }
    num = toString(round(num, 0));
    let numList = [];
    let scaleList = [];
    let res = '';
    for (let digit of num) {
        numList.push(numMap[Number(digit)]);
    }

    let maxScale: number = parseInt(String((num.length - 1) / scale1.length));
    for (let i = (num.length - 1) % scale1.length; i > 0; --i) {
        scaleList.push(scale1[i]);
    }
    for (let i = maxScale; i > 0; --i) {
        scaleList.push(scale2[i]);
        for (let j = scale1.length - 1; j > 0; --j) {
            scaleList.push(scale1[j]);
        }
    }
    for (let index = 0; index < numList.length; ++index) {
        if (numList[index] === '零') {
            res += numList[index];
            continue;
        }
        res += numList[index];
        if (scaleList[index]) {
            res += scaleList[index];
        }
    }
    if (res[0] === '一' && res[1] === '十') {
        res = res.replace(/^一/, '');
    }
    res = res.replace(/零+/, '零');
    return res.replace(/零$/, '');
};

/**
 * 根据 precision（精度） 四舍五入 number(source: _.round)
 *
 * @category Number
 * @param {number} number (number): 要四舍五入的数字
 * @param {number} [precision=0] (number): 四舍五入的精度
 * @returns {number} (number): 返回四舍五入的数字
 * @example
 *
 * round(1.006)
 * // => 1
 *
 * round(1.006, 2)
 * // => 1.01
 *
 * round(1060, -2)
 * // => 1100
 **/
function round(number: number, precision: number | null) {
    precision = precision == null ? 0 : (precision >= 0 ? Math.min(precision, 292) : Math.max(precision, -292))
    if (precision) {
        let pair = `${number}e`.split('e')
        // @ts-ignore
        const value = Math.round(`${pair[0]}e${+pair[1] + precision}`)
        pair = `${value}e`.split('e')
        return +`${pair[0]}e${+pair[1] - precision}`
    }
    return Math.round(number)
}

export {
    num2Chinese,
    round
}
